<template>
    <div class="search">
        <el-card class="search-view">
            <template #header>
                <h4>关键词搜索</h4>
                <el-dropdown>
                    <span class="el-dropdown-link">
                        <el-icon class="el-icon--right">
                            <MoreFilled />
                        </el-icon>
                    </span>
                    <template #dropdown>
                        <el-dropdown-menu>
                            <el-dropdown-item>Action 1</el-dropdown-item>
                            <el-dropdown-item>Action 2</el-dropdown-item>
                            <el-dropdown-item>Action 3</el-dropdown-item>
                            <el-dropdown-item disabled>Action 4</el-dropdown-item>
                            <el-dropdown-item divided>Action 5</el-dropdown-item>
                        </el-dropdown-menu>
                    </template>
                </el-dropdown>
            </template>
            <!-- 折线图结构 -->
            <div class="search-wrap">
                <div class="search-wrap-chart">
                    <div class="chart-title">搜索用户数</div>
                    <div class="chart-value">{{ numberFormat(lineChartData.totalUser) }}</div>
                    <v-chart :option="getLineOption('userList', '搜索用户数')" autoresize></v-chart>
                </div>
                <div class="search-wrap-chart">
                    <div class="chart-title">总的搜索量</div>
                    <div class="chart-value">{{ numberFormat(lineChartData.totalCount) }}</div>
                    <v-chart :option="getLineOption('countList', '总的搜索量')" autoresize></v-chart>
                </div>
            </div>
            <!-- 表格 -->
            <el-table :data="tableData">
                <el-table-column prop="rankNo" label='排名' align="center" />
                <el-table-column prop="word" label="关键字" />
                <el-table-column prop="count" label="搜索数量" />
                <el-table-column prop="user" label="搜索用户数" />
                <el-table-column prop="range" label="搜索占比" />
            </el-table>
            <!-- 分页器 -->
            <el-pagination layout="prev, pager, next" :total="tableTotalData.length" v-model:current-page="currentPage"
                :page-size="pageSize" />
        </el-card>
        <el-card class="search-view" shadow="hover">
            <template #header>
                <h4>分类销售排行</h4>
                <el-radio-group v-model="tabPosition" size="small">
                    <el-radio-button label="品类">品类</el-radio-button>
                    <el-radio-button label="商品">商品</el-radio-button>
                </el-radio-group>
            </template>
            <div class="search-pie">
                <v-chart class="pie-chart" :option="getPieOption()"></v-chart>
            </div>
        </el-card>
    </div>
</template>

<script lang="ts">
export default {

}
</script>

<script setup lang="ts">
import { ref, computed } from 'vue'
import { MoreFilled } from '@element-plus/icons-vue';
import { useReportDataStore } from '@/stores/reportData';
import useFormat from '@/hooks/useFormat';
const { numberFormat, moneyFormat } = useFormat()
const reportDataStore = useReportDataStore();
const currentPage = ref(1);
const pageSize = ref(5);

const tabPosition = ref('品类')

//排行榜
const searchWord = computed(() => reportDataStore.reportData.searchWord);
//分类销售排行榜
const saleRank = computed(() => reportDataStore.reportData.saleRank);
// console.log(saleRank.value)

//重新处理一下数据
const tableTotalData = computed(() => {
    if (!searchWord.value) return []
    return searchWord.value?.map((item, index) => {
        return {
            ...item,
            rankNo: index + 1,
            range: ((item.user / item.count) * 100).toFixed(2) + '%'
        }
    })
})

//表格数据
const tableData = computed(() => {
    return tableTotalData.value.slice((currentPage.value - 1) * pageSize.value, currentPage.value * pageSize.value);
})


//折线图需要的数据
const lineChartData = computed(() => {
    const data = {
        wordList: [] as string[], // 折线图X轴需要用到的数据 两个图共用这一个即可
        userList: [] as number[], // 搜索用户数 其实就是用户访问量折线图Y轴需要用到的数据
        countList: [] as number[], // 搜索量数据 其实就是搜索量折线图Y轴用到的数据
        totalUser: 0, // 搜索用户数总量统计
        totalCount: 0 // 总的搜索量统计
    };

    tableTotalData.value.forEach((item: any) => {
        data.wordList.push(item.word);
        data.userList.push(item.user);
        data.countList.push(item.count);
        data.totalUser += item.user;
        data.totalCount += item.count;
    });

    return data; // 一定一定要注意 要将数据返回
});

//折线图需要的参数
const getLineOption = (listName: 'userList' | 'countList', name: string) => {
    return {
        xAxis: {
            boundaryGap: false, // 左右两侧不留白
            // data: ['一月', '二月', '三月', '四月', '五月', '六月', '七月', '八月', '九月', '十月', '十一月', '十二月'] // x轴数据列表
            data: lineChartData.value.wordList
        },
        yAxis: {
            show: false
        },
        tooltip: {
            trigger: 'axis', // 只要鼠标在x轴就会触发
            confine: true // 显示的内容是在图形内还是图形外
            // true表示在图形内  false 表示在图形外
        },
        // 图表在坐标中显示的位置
        grid: {
            left: 0,
            top: 0,
            right: 0,
            bottom: 0
        },
        series: {
            type: 'line',
            smooth: true, // 让折线更加的平滑
            itemStyle: {
                // 折线点 不要显示
                opacity: 0
            },
            lineStyle: {
                color: '#5FBBFF'
            },
            areaStyle: {
                // 折线图区域内的颜色
                color: '#C7E7FF'
            },
            // data: [44, 126, 55, 88, 133, 99, 33, 113, 63, 98, 77, 123]
            data: lineChartData.value[listName]
        }
    };
};

//准备饼状图相关的数据
const pieChartData = computed(() => {
    const data = {
        categoryList: [] as any, // 品类的数组
        goodsList: [] as any, // 商品的数组
        cTotal: 0, // 品类的总数组
        gTotal: 0 // 商品的总数组
    };

    // 如果没有值的话，就不要再往下走了
    if (!saleRank.value) return {} as any;
    // 从saleRank中解构相关的数据出来 然后循环遍历 添加到piChartData中
    const {
        category: { axisX, data1 },
        goods: { axisX: axisX2, data1: data2 }
    } = saleRank.value;

    // console.log(axisX, axisX2)

    // 去准备数组 先准备数量的数据
    // console.log('aab',axisX, data1, axisX2, data2);
    const total1 = data1.reduce((prev, item) => prev + item, 0);
    data.cTotal = total1; //累计订单量：品类
    const total2 = data2.reduce((prev, item) => prev + item, 0);
    data.gTotal = total2; //累计订单量：商品

    // 准备每个分类中的数组内容项
    axisX.forEach((item, index) => {
        const percent = ((data1[index] / total1) * 100).toFixed(2) + '%';
        data.categoryList.push({
            name: item + '|' + percent,
            labelName: item,
            value: data1[index],
            percent
        });
    });

    axisX2.forEach((item, index) => {
        const percent = ((data2[index] / total2) * 100).toFixed(2) + '%';
        data.goodsList.push({
            name: item + '|' + percent,
            labelName: item,
            value: data2[index],
            percent
        });
    });
    return data;
});

//饼状图渲染时的参数
const getPieOption = () => {
    const list = tabPosition.value === '品类' ? pieChartData.value.categoryList : pieChartData.value.goodsList;
    const text = tabPosition.value === '品类' ? '品类分布' : '商品分布';
    const subtext = tabPosition.value === '品类' ? pieChartData.value.cTotal : pieChartData.value.gTotal; //累计订单量
    return {
        title: [
            {
                text,
                textStyle: {
                    fontSize: 14,
                    color: '#666'
                },
                left: 20,
                top: 20
            },
            {
                text: '累计订单量',
                textStyle: {
                    fontSize: 14,
                    color: '#999'
                },
                subtext,
                subtextStyle: {
                    fontSize: 36,
                    color: '#333'
                },
                left: '34.5%',
                top: '42.5%',
                textAlign: 'center'
            }
        ],
        tooltip: {
            trigger: 'item',
            formatter: (params: any) => {
                // console.log('pp', params);
                return `${tabPosition.value}分布<br/>
          ${params.marker + params.data.labelName}<br/>
          ${params.marker}数量:${params.data.value}<br/>
          ${params.marker}占比:${params.data.percent}<br/>
        `;
            }
        },
        legend: {
            // 图例列表的布局朝向
            orient: 'vertical',
            top: 'middle',
            left: '70%',
            textStyle: {
                color: '#8c8c8c'
            }
        },
        series: [
            {
                name: 'Access From',
                type: 'pie',
                radius: ['39%', '57%'],
                center: ['35%', '50%'],
                avoidLabelOverlap: false,
                itemStyle: {
                    // borderRadius: 10,
                    borderColor: '#fff',
                    borderWidth: 2
                },
                label: {
                    show: true,
                    position: 'outside',
                    formatter: function (params: any) {
                        // console.log(params);
                        return params.data.labelName;
                    }
                },
                //引导线的设置
                labelLine: {

                    length: 7,
                    length2: 5
                },

                data: list
            }
        ]
    };
};

</script>

<style scoped lang="scss">
.search {
    display: flex;
    margin-top: 20px;

    .search-view {
        flex: 1;
        cursor: pointer;

        &:first-child {
            margin-right: 20px;

            .search-wrap {
                .search-wrap-chart {
                    display: inline-block;
                    width: 50%;

                    &:first-child {
                        padding-right: 10px;
                    }

                    .chart-title {
                        font-size: 14px;
                        color: #999;
                    }

                    .chart-value {
                        font-size: 24px;
                        line-height: 26px;
                        letter-spacing: 1px;
                    }

                    // 折线图的高度
                    .echarts {
                        height: 50px;
                    }
                }
            }
        }

        &:last-child {
            .search-pie {
                .pie-chart {
                    width: 100%;
                    height: 400px;
                }
            }
        }

        :deep(.el-card__header) {
            padding: 0 20px;
            display: flex;
            justify-content: space-between;
            align-items: center;

            h4 {
                font-size: 16px;
                font-weight: 500;
            }
        }
    }
}
</style>